<template>
  <div v-loading="loading">
    <el-row type="flex" justify="space-between">
      <el-col :span="6">
        <el-row type="flex" justify="space-between">
          <el-col :span="6">
            <div class="current">
              <span v-if="isNow" class="gl_fs_14">本天</span>
              <span v-else class="gl_fs_14">非本天</span>
            </div>
          </el-col>
          <el-col :span="16" align="right"><div class="class_name gl_ellipsis">{{ className }}</div></el-col>
        </el-row>
      </el-col>
      <el-col :span="12">
        <div class="date">
          <el-button size="mini" class="left_right_btn" type="text" icon="el-icon-arrow-left" @click="toPrev()" />
          <span class="gl_dis_ib gl_middle">{{ currentDate }}</span>
          <el-button size="mini" class="left_right_btn" type="text" @click="toNext()">
            <i class="el-icon-arrow-right el-icon--right" />
          </el-button>
        </div>
      </el-col>
      <el-col :span="6" class="gl_fs_14" align="right">
        <span class="type" :class="[ typeTimeTable == 'day' ? 'type_active': '' ]" @click="changeType('day')">日</span>
        <span class="type" :class="[ typeTimeTable == 'week' ? 'type_active': '' ]" @click="changeType('week')">周</span>
        <span class="type" :class="[ typeTimeTable == 'month' ? 'type_active': '' ]" @click="changeType('month')">月</span>
      </el-col>
    </el-row>
    <div class="gl_mt_5 timetable_day">
      <el-table
        :data="classList"
        :show-header="false"
      >
        <el-table-column prop="course" width="60" />
        <el-table-column prop="data">
          <template slot-scope="{ row }">
            <div v-if="row.data && row.data.length > 0">
              <template v-for="(ctem, cndex) in row.data">
                <div :key="cndex" class="gl_dis_ib class_td" :style="{ width: 100 / row.data.length + '%', background: ctem.courseScheduleColor }">
                  <Hover :is-order-page="isOrderPage" :class-name="ctem.className" :data="ctem" :week="String(week)" @edit="edit" @remove="remove">
                    <div slot="content" class="ellipsis" @click="toClassTimetable(ctem)">
                      <span>{{ classId ? ctem.courseName : ctem.className }}</span>
                    </div>
                  </Hover>
                </div>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <CreateDialog ref="createDialog" @refresh="refresh" />
  </div>
</template>

<script>
import Hover from '../hover.vue';
import CreateDialog from '@/components/Class/createDialog.vue';
import {
  api_GET_ClubCourseSchedule, // 获取课表
  api_GET_ClubCourseScheduleCanBeReservedCourseSchedules, // 预约
  api_DELETE_ClubCourseScheduleId
} from '@/extend/api/hallswaggerApi/app.js';
import {
  Api_GET_ClubCourseScheduleQO
} from '@/lib/form/hall/swaggerForm.js';
export default {
  components: {
    Hover,
    CreateDialog
  },
  props: {
    typeTimeTable: {
      type: String,
      default: 'week'
    },
    searchForm: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      loading: false,
      form: new Api_GET_ClubCourseScheduleQO(),
      nowDay: '', // 今天
      currentDate: '', // 当前天
      currentDateCopy: '', // 当前天(new Date格式)
      isOrderPage: false, // 是否是预约管理页面
      className: '',
      classId: '',
      initClassList: [
        {
          course: '5:00',
          data: []
        },
        {
          course: '6:00',
          data: []
        },
        {
          course: '7:00',
          data: []
        },
        {
          course: '8:00',
          data: []
        },
        {
          course: '9:00',
          data: []
        },
        {
          course: '10:00',
          data: []
        },
        {
          course: '11:00',
          data: []
        },
        {
          course: '12:00',
          data: []
        },
        {
          course: '13:00',
          data: []
        },
        {
          course: '14:00',
          data: []
        },
        {
          course: '15:00',
          data: []
        },
        {
          course: '16:00',
          data: []
        },
        {
          course: '17:00',
          data: []
        },
        {
          course: '18:00',
          data: []
        },
        {
          course: '19:00',
          data: []
        },
        {
          course: '20:00',
          data: []
        },
        {
          course: '21:00',
          data: []
        },
        {
          course: '22:00',
          data: []
        },
        {
          course: '23:00',
          data: []
        },
        {
          course: '24:00',
          data: []
        }
      ],
      week: '',
      classList: [],
      isNow: true // // 是否为本天、本周、本月
    };
  },
  watch: {
    typeTimeTable: {
      immediate: true,
      handler(val) {
        if (val === 'day') {
          const date = new Date();
          this.className = this.$route.params.classId ? this.$route.query.name : '';
          this.classId = this.$route.params.classId || '';
          this.nowDay = this.formatDate(date);
          this.currentDate = this.nowDay;
          this.currentDateCopy = date;
        }
      }
    },
    searchForm: {
      immediate: true,
      deep: true,
      handler(val) {
        // 是否是预约页面
        if (this.$route.path.indexOf('/selectAppointmentClass') > 0) {
          this.isOrderPage = true;
          this.getOrderData();
        } else {
          this.isOrderPage = false;
          this.getData();
        }
      }
    },
    // 监测当前天是否为本天，日期改变重新获取数据
    currentDate: {
      immediate: true,
      handler(val) {
        this.isNow = val === this.nowDay;
        if (this.$route.path.indexOf('/selectAppointmentClass') > 0) {
          this.isOrderPage = true;
          this.getOrderData();
        } else {
          this.isOrderPage = false;
          this.getData(this.classId);
        }
        const week = this.currentDateCopy.getDay();
        this.week = week > 0 ? week : 7;
      }
    }
  },
  created() {
    // 是否是预约页面
    if (this.$route.path.indexOf('/selectAppointmentClass') > 0) {
      this.isOrderPage = true;
    }
  },
  methods: {
    changeType(code) {
      this.$emit('changeType', code);
    },
    // 当前页面为课表时
    getData(id) {
      var that = this;
      that.loading = true;
      if (this.$route.path.indexOf('/trialclass') > 0) {
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var day = now.getDate();
        console.log(year, month, day);
        that.form.StartTime = year + '-' + month + '-' + day;
      } else {
        that.form.StartTime = that.formatParam(that.currentDate);
      }

      that.form.EndTime = that.formatParam(that.currentDate);
      that.form.CourseName = that.searchForm.CourseName;
      that.form.TeachingModeCode = that.searchForm.TeachingModeCode;
      that.form.CoachName = that.searchForm.CoachName;
      that.form.IsFinished = null;
      that.form.IncludeClass = true;
      that.form.IncludeCourse = true;
      that.form.IncludeCoach = true;
      that.form.IncludeClassroom = true;
      that.form.IncludeMessageTemplate = true;
      that.form.IncludeDeleted = true;
      that.form.ClassId = id || null;
      that.form.SkipCount = null;
      that.form.MaxResultCount = null;
      const time = that.form.StartTime + '~' + that.form.EndTime;
      that.$emit('getTime', time);
      api_GET_ClubCourseSchedule(that.form).then(res => {
        that.handlerData(res.items);
        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 当前页面为预约时
    getOrderData() {
      var that = this;
      that.loading = true;
      const form = {
        CourseName: that.searchForm.CourseName,
        TeachingModeCode: that.searchForm.TeachingModeCode,
        StudentId: that.$route.query.studentId,
        StartTime: that.formatParam(that.currentDate),
        EndTime: that.formatParam(that.currentDate)
      };
      api_GET_ClubCourseScheduleCanBeReservedCourseSchedules(form).then(res => {
        that.handlerData(res);
        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    handlerData(array) {
      this.classList = JSON.parse(JSON.stringify(this.initClassList));
      for (let i = 0; i < array.length; i++) {
        const item = array[i];
        // let startHour = item.startHour < 10 ? '0' + item.startHour : item.startHour;
        const startHour = item.startHour + ':00';
        const key = this.classList.findIndex(ctem => ctem.course === startHour);
        if (key !== -1) {
          this.classList[key].data.push(item);
        }
      }
    },
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear() + '年';
      const month = (date.getMonth() + 1) + '月';
      const day = date.getDate() + '日';
      return year + month + day;
    },
    // 去往班课表
    toClassTimetable(row) {
      if (this.$route.path.indexOf('/trialclass') > 0) {
        return;
      }
      if (!this.isOrderPage) {
        const params = {
          classId: row.classId
        };
        this.$router.push({
          name: 'ClassTimetable',
          params: params,
          query: {
            name: row.className
          }
        });
      }
    },
    // 改变日期
    changeDate (date, n) {
      const currentTime = date.getTime();
      const ms = 24 * 3600 * 1000 * n;
      date.setTime(parseInt(currentTime + ms));
      this.currentDateCopy = date;
      const oYear = date.getFullYear();
      const oMoth = (date.getMonth() + 1).toString();
      // if (oMoth.length <= 1) oMoth = '0' + oMoth;
      const oDay = date.getDate().toString();
      // if (oDay.length <= 1) oDay = '0' + oDay;
      return oYear + '年' + oMoth + '月' + oDay + '日';
    },
    // 格式化请求时的日期格式
    formatParam(date) {
      const y = date.split('年')[0];
      let str = date.split('年')[1];
      const m = str.split('月')[0];
      str = str.split('月')[1];
      const d = str.split('日')[0];
      return y + '-' + m + '-' + d;
    },
    toPrev() {
      this.currentDate = this.changeDate(this.currentDateCopy, -1);
    },
    toNext() {
      this.currentDate = this.changeDate(this.currentDateCopy, 1);
    },
    // 删除
    remove(data) {
      var that = this;
      that.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api_DELETE_ClubCourseScheduleId(data.id).then(res => {
          that.getData(that.classId);
          that.$message({ type: 'success', message: '删除成功!' });
        }).catch(error => {
          that.$message({ type: 'error', message: '删除失败 ' + error.error.message });
        });
      }).catch(() => {});
    },
    refresh() {
      this.getData(this.classId);
    },
    // 编辑
    edit(data) {
      this.$refs.createDialog.open('编辑', data);
    }
  }
};
</script>

<style lang="scss">
.timetable_day {
  /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
  ::-webkit-scrollbar{
    width: 6px;
    height: 6px;
  }
  /*定义滚动条轨道 内阴影+圆角*/
  ::-webkit-scrollbar-track {
    background-color: transparent;
  }
  /*定义滑块 内阴影+圆角*/
  ::-webkit-scrollbar-thumb{
    border-radius: 12px;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
    background-color: rgba(144, 147, 153, 0.3);
  }
  .el-table {
    border: none;
    border-right: none !important;
  }
  .el-table tr td {
    height: 72px;
    padding: 0 0;
  }
  .el-table tr td:not(:first-child) .cell{
    height: 72px;
    padding: 0;
    height: 100%;
  }
  .el-table tr td:first-child {
    border: none;
    font-size: 12px;
    text-align: right;
    color: #71717a;
    line-height: 16px;
    position: relative;
    top: -16px;
  }
  // 取消第一列的hover背景色
  .el-table tbody tr:hover>td:first-child {
    background-color: transparent !important
 }
}
</style>

<style scoped>
.current {
  width: 60px;
  height: 28px;
  background: #f4f4f5;
  line-height: 28px;
  text-align: center;
  color: #18181b;
  border-radius: 6px;
}
.left_right_btn {
  width: 28px;
  height: 28px;
  color: #18181b;
}
.date {
  width: 100%;
  height: 28px;
  line-height: 28px;
  text-align: center;
  color: #333333;
  font-size: 18px;
  font-weight: 500;
  cursor: pointer;
  vertical-align: middle;
}
.type {
  width: 46px;
  height: 28px;
  border-radius: 8px;
  cursor: pointer;
  padding: 4px 16px;
  color: #71717a;
  line-height: 20px;
}
.type_active {
  background: #1990ff;
  color: #ffffff;
}
.class_td {
  height: 72px;
  padding: 4px;
  color: #ffffff;
  vertical-align: top;
  line-height: 14px;
  box-sizing: border-box;
  border-radius: 4px;
  border: 1px solid #ffffff;
  overflow: hidden;
}
.ellipsis {
  height: 56px;
  /* display: -webkit-box; */
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
}
.class_name {
  height: 28px;
  line-height: 28px;
  color: #1990ff;
  font-size: 16px;
  font-weight: 600;
  vertical-align: middle;
}
</style>
